$(function () {
    // 开始写 jQuery 代码...
    // var codeBtn = document.getElementById('code-btn');
    // console.log(codeBtn);
    // codeBtn.addEventListener('click', function() {
    //     alert("aaa");
    //   var email = document.getElementById("username").value;
    //   if(!email){
    //       alert("请填写正确的邮箱地址！")
    //       return;
    //   }
    //   var urlstr = "./api/code/create/" + email;
    //   $.ajax({
    //     type:"post",
    //     url: urlstr,
    //     success: function (data) {
    //         alert(data);
    //       }
    //   },);
    // })
    $("#code-btn").click(function () {
        var emailStr = document.getElementById("username").value;
        console.log(emailStr);
        if (!emailStr) {
            alert("请填写邮箱地址！")
            return;
        }
        var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;
        if(reg1.test(emailStr) == false) {
            alert('邮箱格式不正确');
            return false;
        }
        var urlstr = "/api/code/create/" + emailStr;
        $.ajax({
            type: "post",
            url: urlstr,
            data: { email: emailStr },
            success: function (data) {
                document.getElementById("msg").innerText = data.msg;
            }
        });
    });

    $("#register-btn").click(function () {
        var emailStr = document.getElementById("username").value;
        var passwordStr = document.getElementById("password").value;
        var codeStr = document.getElementById("auth_code").value;


        console.log(emailStr);
        console.log(passwordStr);

        if (!emailStr) {
            alert("请填写邮箱地址！")
            return;
        }
        var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;
        if(reg1.test(emailStr) == false) {
            alert('邮箱格式不正确');
            return false;
        }
        if (!codeStr) {
            alert("请输入密码！")
            return;
        }
        if (!passwordStr) {
            alert("请输入验证码！")
            return;
        }

        var urlstr = "/api/user/register/" + emailStr
            + "/" + passwordStr + "/" + codeStr;
        $.ajax({
            type: "post",
            url: urlstr,
            data: {
                email: emailStr,
                password: passwordStr,
                code: codeStr
            },
            success: function (data) {
                //   alert(data);
                if(data.code == 200){
                    location.href = "index.html";
                }else{

                    if(data.msg){
                        document.getElementById("msg").innerText = data.msg;
                    }else{
                        var res = JSON.parse(data);

                        document.getElementById("msg").innerText = res.msg;
                    }
                }
            }
        });
    });
});